package com.shamar.blog.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

/**
 * @author zhy
 * @date 2020-1-2
 * @descrption ID生成类
 */
public class IdGenerate {
    private static final Logger log = LoggerFactory.getLogger("IdGenerate");
    private final long twepoch = 1288834974657L;
    private static final int sequenceMask = 9;

    private static int sequence = 0;
    private static long lastTimestamp = -1L;

    private static Random random = new Random();

    private String serverIds;

    /**
     * 计算毫秒内的序列号
     */
    public synchronized static String nextId() {
        long timestamp = timeGen();
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }
        if (lastTimestamp == timestamp) {
            if (sequence == sequenceMask) {
                sequence = 0;
                timestamp = tilNextMillis(lastTimestamp);
            } else {
                sequence = sequence + 1;
            }
        } else {
            sequence = 0;
        }

        lastTimestamp = timestamp;
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(timestamp);
        Date date1 = c.getTime();
        return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(date1) + String.format("%01d", sequence);
    }

    protected static long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    protected static long timeGen() {
        return System.currentTimeMillis();
    }

    /**
     * 获得服务器编号 192.168.0.105:05,192.168.0.106:06
     */
    public String getServerId() {
        String ip = IPUtil.firstIp();
        if (!StringUtils.isEmpty(serverIds)) {
            String servers[] = serverIds.split(",");
            for (String ser : servers) {
                String[] arr = ser.split(":");
                if (ip.equals(arr[0])) {
                    return arr[1];
                }
            }
        } else {
            log.info("serverIds is null");
        }
        return "00";
    }

    /**
     * 生成订单号 数据库编号+表编号+yyyyMMddHHmmssSSS+序列号+服务器编号
     */
    public static String getOrderId() {
        try {
            String id = nextId();
            String transTime = id.substring(0, 8);
            Integer time = Integer.valueOf(transTime) * (16 + 1);
//            return String.format("%02d", random.nextInt(99)) + ShardUtil.getDBInfoByDate(time) + ShardUtil.getTableInfoByDate(time) + id + getServerId();
            return String.format("%02d", random.nextInt(99)) + ShardUtil.getDBInfoByDate(time) + ShardUtil.getTableInfoByDate(time) + id + String.format("%02d", random.nextInt(99));
        } catch (Exception e) {
            log.error("getOrderId Exception:", e);
        }

        return null;
    }

    public static void main(String[] args) {
        System.out.println(nextId());
    }
}